﻿using System.Collections.Generic;
using KamLib;

namespace KamLib
{
    /// <summary>
    /// Говорит о том, что это один из главных UI-классов (главная страница, форма)
    /// </summary>
    public interface IUilView
    {
        UilController Controller { get; set; }
        IList<IUilViewPart> Parts { get; set; }
        void AdaptToController();
    }

    /// <summary>
    /// 
    /// </summary>
    public interface IUilViewPart : IUilView
    {
        string Name { get; }
    }


    public static class UilView
    {

        /// <summary>
        /// Inits as main.
        /// </summary>
        /// <param name="view">The view.</param>
        /// <param name="controller">The controller.</param>
        public static void InitAsMain(IUilView view, UilController controller)
        {
            controller.InitView(view);
            AdaptToController(view);
        }

        /// <summary>
        /// Inits as main.
        /// </summary>
        /// <param name="view">The view.</param>
        /// <param name="key">The key.</param>
        public static void InitAsMain(IUilView view, UilKey key)
        {
            using (var context = new UilContext())
            {
                var ctrl = view.Controller = context.GetController(key);
                InitAsMain(view, ctrl);
            }
        }

        /// <summary>
        /// Inits as main.
        /// </summary>
        /// <typeparam name="TController">The type of the controller.</typeparam>
        /// <param name="view">The view.</param>
        public static void InitAsMain<TController>(IUilView view)
            where TController : UilController
        {
            using (var context = new UilContext())
            {
                var ctrl = view.Controller = context.New<TController>();
                InitAsMain(view, ctrl);
            }
        }

        /// <summary>
        /// Adapts to controller.
        /// </summary>
        /// <param name="view">The view.</param>
        public static void AdaptToController(IUilView view)
        {
            if (view == null) return;
            view.AdaptToController();

            var parts = view.Parts;
            if (parts == null) return;
            foreach (var part in parts)
            {
                AdaptToController(part);
            }
        }

    }

}